<?php
/**前台登录模型
 * Created by PhpStorm.
 * User: xiangpeng
 * Date: 2017/1/5
 * Time: 0:51
 */

namespace Common\Model;


use Think\Model;

class LoginModel extends Model
{
    //主键
    protected  $pk = 'uid';
    //要操作那张表
    protected  $tableName = 'yuser';
    //自动验证
    protected $_validate=[
        ['account','require','账号不能为空',1,3],
        ['password','require','密码不能为空',1,3],
        ['password1','require','请确认密码',1,3],
    ];

    //注册方法
    public function register(){
        //1获得页面提交的验证码
        $data=I('post.');
        //var_dump($res);die;
        if(!$this->check_verify($data['code'])){
            return ['status'=>'faild','message'=>'验证码错误'];die;

        }
        //执行验证
        if(!$this->create()){
            return ['status'=>'faild','message'=>$this->getError()];die;
        }
        $data=[
            'account' =>$_POST['account'],
            'password' =>md5($_POST['password']),
        ];
        if($data['password']!=md5($_POST['password1'])){
            return ['status'=>'faild','message'=>'两次密码不一致'];
        }
        //判断用户是否已经被注册
        $account =$this->where("account='{$_POST['account']}'")->find();
        if($account){
                return ['status'=>'faild','message'=>'用户名已经被注册'];
        }
        //2.2执行添加
        $uid = $this->add($data);
        return ['status'=>'success','message'=>'注册成功'];

    }


    //登录方法
    public function isLogin(){
        //获得页面提交的验证码
        $data = I('post.');
        if(!$this->check_verify($data['code'])){
            return ['status'=>'faild','message'=>'验证码错误'];
        }
        //判断用户是否存在
        $user = $this->where("account='{$data['account']}'")->find();
        if(!$user){
            return ['status'=>'faild','message'=>'用户名不存在'];
        }
        //比对用户名和密码
        $password = md5($_POST['password']);
        $res = $this->where("account='{$_POST['account']}'")->where("password='{$password}'")->find();
       //dd($res);DIE;
        if(!$res){
            return ['status'=>'faild','message'=>'用户名或密码错误'];
        }
        //将session存入
        session('home.uid',$res['uid']);
        session('home.name',$res['account']);
        return ['status'=>'success','message'=>'登录成功'];
    }

    // 检测输入的验证码是否正确，$code为用户输入的验证码字符串
    protected function check_verify($code, $id = ''){
        $verify = new \Think\Verify();
        return $verify->check($code, $id);
    }
}
